package com.cy.detectsys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cy.detectsys.entity.TcPackage;
import com.cy.detectsys.entity.TcTask;
import com.cy.detectsys.mapper.TcTaskMapper;
import com.cy.detectsys.model.PageDto;
import com.cy.detectsys.model.PageReqModel;
import com.cy.detectsys.model.vo.TcPackageVO;
import com.cy.detectsys.service.TcPackageService;
import com.cy.detectsys.mapper.TcPackageMapper;
import com.cy.detectsys.service.TcTaskService;
import com.cy.detectsys.util.R;
import com.github.pagehelper.PageHelper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
* @author admin
* @description 针对表【tc_package】的数据库操作Service实现
* @createDate 2024-05-08 00:57:52
*/
@Service
public class TcPackageServiceImpl extends ServiceImpl<TcPackageMapper, TcPackage>
    implements TcPackageService{

    @Resource
    private TcTaskMapper tcTaskMapper;

    @Override
    public R list(PageReqModel pageReqModel) {

        PageHelper.startPage(pageReqModel.getPage(), pageReqModel.getPageSize());
        QueryWrapper<TcPackage> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        List<TcPackage> tcPackages =
                baseMapper.selectList(queryWrapper);

        //DTO 转 VO
        PageDto<TcPackageVO> tcPackageVOS = PageDto.listToPageVO(tcPackages, TcPackageVO.class);

        //补充探测信息
        for (TcPackageVO tcPackage : tcPackageVOS.getData()) {
            QueryWrapper<TcTask> packageQuery = new QueryWrapper<>();
            packageQuery.eq("package_id", tcPackage.getId());
            List<TcTask> tcTasks = tcTaskMapper.selectList(packageQuery);
            tcPackage.setTasks(tcTasks);

            if (tcPackage.getStatus().equals("任务执行中")) {
                //检查task状态
                boolean flag = tcTasks.stream().filter(item -> item.getStatus().equals("执行中")).findFirst().isPresent();
                if (!flag) {
                    //    表示 配置包下全部的数据都是 已完成状态
                    tcPackage.setStatus("任务已完成");
                    new Thread(() -> {
                        TcPackage tcPackageDto = BeanUtil.copyProperties(tcPackage, TcPackage.class);
                        baseMapper.updateById(tcPackageDto);
                    }).start();

                }
            }
        }

        return R.ok(tcPackageVOS);
    }

}




